<?php

/*===============微信商城=================*/
/*----------------------------------------*/
/* $Author: 疯中追风                      */
/*----------------------------------------*/
/* $Time: 2017/10/16 16:06                */
/*----------------------------------------*/
/*=============用户表相关表===============*/

namespace   Pc\Controller;
use  Think\Controller;

class UserController  extends  Controller{
    //获取登录信息
    public function login(){
    	if(IS_POST){
    		$post = I('post.');
    		//查询salt值
    		$salt = M('User') -> where(array('mobile' =>$post['mobile'])) -> find()['salt'];
    		//进行MD5加密,并查询
    		$post['password'] = md5($salt.$post['password']);
    		$result = M('User') -> where($post) -> find();
    		//获取ip地址
            $ip = get_client_ip();
            //获取最后登录时间
            $date = getdate(date("U"));
            $current_date = $date[year].'-'.($date[mon]).'-'.$date[mday]." "."  ".$date[hours].':'.$date[minutes].':'.$date[seconds];
            
            //插入数据库
            M('User') -> save(array('user_id'=>$result['user_id'],'last_login'=>$current_date,'last_ip'=>$ip));
    		if($result == true){
    			//登录成功直接跳转首页
    			$username = $result['username'];
    			$id = $result['id'];
    			session('username',$username);
    			session('id',$id);
    			redirect(U('Index/index'));
    		}else{
    			echo "登录失败,请检查用户名或密码";
    		}
    	}else{
    		$this -> display();
    	}
    }

    //注册
    public function register(){
    	$post = I('post.');
    	//首先判断手机号是否已经被注册
    	$mobile = M('User') -> where(array('mobile' => $post['mobile'])) -> find();
    	if($mobile == true){
    		echo "<script>alert('你输入账号已经注册！')</script>";
    	}else{
	    	//对传入的密码md5加盐加密
	    	//生成随机字符串;
	    	$salt  =  create_salt();
	    	$post['salt'] = $salt;
	    	$post['password'] = md5($salt.$post['password']);
	    	//去掉多余的字段
	    	unset($post['verify']);
	    	unset($post['password2']);
	    	$result = M('User') -> add($post);
	    	if($result == true){
	    		echo '注册成功！请前往首页进行登录';
	    	}else{
	    		echo '注册失败！';
	    	}
    	}
    }

    //通过扫描微信二维码进行登录
    public function get_erweima(){
    	$ip = get_client_ip();
    	dump($ip);die;
    }

    //退出登录
    public function quit(){
    	session(null);
    	redirect(U('Index/index'));
    }
}
?>